import Router from "koa-router";
import service from "../../service/model/index.js";
import serviceField from "../../service/field/index.js";

import response from "../../response.js";
import _ from "lodash";

const router = new Router();

router.post("/", async (ctx) => {
  try {
    const data = ctx.data;
    if (!data?.name) {
      ctx.body = response.fail({ msg: "name not empty" });
      return;
    }
    if (!data?.list?.length) {
      ctx.body = response.fail({ msg: "list not empty" });
      return;
    }
    const { affectedRows, id } = await service.save([[data?.name]]);
    if (!affectedRows) {
      ctx.body = response.fail({ msg: "fail" });
      return;
    }
    const saveData = data?.list?.map((item) => {
      return [item?.name, item?.type, item?.label, id];
    });

    const result = await serviceField.save(saveData);
    if (!result) {
      ctx.body = response.fail({ msg: "fail" });
    } else {
      ctx.body = response.success({ msg: "success" });
    }
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: "fail" });
  }
});
router.put("/", async (ctx) => {
  try {
    const data = ctx.data;
    if (_.isNil(data?.id)) {
      ctx.body = response.fail({ msg: "id not empty" });
      return;
    }
    if (!data?.list?.length) {
      ctx.body = response.fail({ msg: "list not empty" });
      return;
    }
    const rows = await service.findById(data?.id);
    if (!rows?.length) {
      ctx.body = response.fail({ msg: `id not in data` });
      return;
    }

    const isUpdate = await service.update(data?.id, { name: data?.name });
    if (!isUpdate) {
      ctx.body = response.fail({ msg: "fail" });
      return;
    }

    const delResult = await serviceField.delByModelId(data?.id);
    if (!delResult) {
      ctx.body = response.fail({ msg: "fail" });
      return;
    }
    //`name`,`type`,`label`,`model_id`
    const saveData = data?.list.map((item) => {
      return [item?.name, item?.type, item?.label, data?.id];
    });
    const result = await serviceField.save(saveData);

    if (!result) {
      ctx.body = response.fail({ msg: "fail" });
    } else {
      ctx.body = response.success({ msg: "success" });
    }
    ctx.body = response.success({ msg: "success" });
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: "fail" });
  }
});
router.get("/list", async (ctx) => {
  const list = await service.getList();
  ctx.body = response.success({ data: { list: list } });
});
router.delete("/:id", async (ctx) => {
  const { id } = ctx.params || {};
  if (!id && id !== 0) {
    ctx.body = response.fail({ msg: "id not empty" });
    return;
  }
  const has = await service.findById(id);

  if (!has?.length) {
    ctx.body = response.fail({ msg: `${id} not in data` });
    return;
  }
  const result = await service.del(id);
  if (result) {
    ctx.body = response.success({ msg: "success" });
  } else {
    ctx.body = response.fail({ msg: "fail" });
  }
});
export default router;
